package com.autoglm.data.local.dao

import androidx.room.*
import com.autoglm.data.local.entity.TaskEntity
import com.autoglm.data.model.TaskStatus
import kotlinx.coroutines.flow.Flow
import java.util.Date

/**
 * 任务数据访问对象
 */
@Dao
interface TaskDao {
    
    @Query("SELECT * FROM tasks ORDER BY createdAt DESC")
    fun getAllTasks(): Flow<List<TaskEntity>>
    
    @Query("SELECT * FROM tasks WHERE id = :taskId")
    suspend fun getTaskById(taskId: String): TaskEntity?
    
    @Query("SELECT * FROM tasks WHERE status = :status ORDER BY createdAt DESC")
    fun getTasksByStatus(status: TaskStatus): Flow<List<TaskEntity>>
    
    @Query("SELECT * FROM tasks WHERE status IN (:statuses) ORDER BY createdAt DESC")
    fun getTasksByStatuses(statuses: List<TaskStatus>): Flow<List<TaskEntity>>
    
    @Query("SELECT * FROM tasks WHERE description LIKE :query OR userInput LIKE :query ORDER BY createdAt DESC")
    fun searchTasks(query: String): Flow<List<TaskEntity>>
    
    @Query("SELECT * FROM tasks WHERE createdAt BETWEEN :startDate AND :endDate ORDER BY createdAt DESC")
    fun getTasksByDateRange(startDate: Date, endDate: Date): Flow<List<TaskEntity>>
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertTask(task: TaskEntity)
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertTasks(tasks: List<TaskEntity>)
    
    @Update
    suspend fun updateTask(task: TaskEntity)
    
    @Delete
    suspend fun deleteTask(task: TaskEntity)
    
    @Query("DELETE FROM tasks WHERE id = :taskId")
    suspend fun deleteTaskById(taskId: String)
    
    @Query("DELETE FROM tasks WHERE status = :status")
    suspend fun deleteTasksByStatus(status: TaskStatus)
    
    @Query("DELETE FROM tasks WHERE createdAt < :cutoffDate")
    suspend fun deleteOldTasks(cutoffDate: Date)
    
    @Query("SELECT COUNT(*) FROM tasks")
    suspend fun getTaskCount(): Int
    
    @Query("SELECT COUNT(*) FROM tasks WHERE status = :status")
    suspend fun getTaskCountByStatus(status: TaskStatus): Int
}
